using System;
using System.Waf.Applications;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace TrackMe.View.Behaviours
{
    public static class ListBoxBehaviourLikeAutoComplete
    {
        public static readonly DependencyProperty SelectCmdProperty =
            DependencyProperty.RegisterAttached(
            "SelectCmd",
            typeof(ICommand),
            typeof(ListBoxBehaviourLikeAutoComplete),
            new UIPropertyMetadata(null));

        public static bool GetActive(ListBox control)
        {
            return (bool)control.GetValue(ActiveProperty);
        }

        public static void SetActive(ListBox control, bool value)
        {
            control.SetValue(ActiveProperty, value);
        }

        public static readonly DependencyProperty ActiveProperty =
            DependencyProperty.RegisterAttached(
            "Active",
            typeof(bool),
            typeof(ListBoxBehaviourLikeAutoComplete),
            new UIPropertyMetadata(false, OnActiveChanged));


        private static void OnActiveChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var listBox = d as ListBox;
            if (listBox == null)
                return;

            if (e.NewValue is bool == false)
                return;

            if ((bool)e.NewValue)
            {
                d.SetValue(SelectCmdProperty, new DelegateCommand(param =>
                {
                    var key = (Key) param;
                    switch (key)
                    {
                        case Key.Down:
                            listBox.SelectedIndex = Math.Min(listBox.SelectedIndex + 1, listBox.Items.Count-1);
                            break;
                        case Key.PageDown:
                            listBox.SelectedIndex = Math.Min(listBox.SelectedIndex + 10, listBox.Items.Count-1);
                            break;
                        case Key.Up:
                            listBox.SelectedIndex = Math.Max(listBox.SelectedIndex - 1, 0);
                            break;
                        case Key.PageUp:
                            listBox.SelectedIndex = Math.Max(listBox.SelectedIndex - 10, 0);
                            break;
                    }
                    if (listBox.SelectedItem != null)
                        listBox.ScrollIntoView(listBox.SelectedItem);

                }));
            }else
            {
                d.ClearValue(SelectCmdProperty);
            }
        }
    }
}